package com.xujie.controller;

import com.xujie.common.response.Result;
import com.xujie.common.utils.DateUtils;
import com.xujie.controller.dto.WeatherStatsResponse;
import com.xujie.domain.service.WeatherStatsService;
import com.xujie.infra.entity.WeatherStats;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/weather/stats")
public class WeatherStatsController {

  @Autowired
  private WeatherStatsService weatherStatsService;

  /**
   * 获取指定城市未来7天的天气统计数据
   * 
   * @param city 城市名称
   * @return 天气统计数据
   */
  @GetMapping("/forecast")
  public Result<List<WeatherStatsResponse>> getFutureWeatherStats(
      @RequestParam(defaultValue = "成都", name = "city") String city) {
    try {
      log.info("获取{}未来7天天气统计数据", city);

      // 计算日期范围
      Calendar calendar = Calendar.getInstance();
      Date startDate = DateUtils.getStartOfDay(calendar.getTime());

      calendar.add(Calendar.DAY_OF_MONTH, 7); // 加6天，总共7天
      Date endDate = calendar.getTime();

      // 获取天气数据
      List<WeatherStats> statsList = weatherStatsService.getWeatherStats(city, startDate, endDate);

      // 转换为响应DTO
      List<WeatherStatsResponse> responseList = statsList.stream()
          .map(stats -> {
            WeatherStatsResponse response = new WeatherStatsResponse();
            BeanUtils.copyProperties(stats, response);
            return response;
          })
          .collect(Collectors.toList());

      return Result.success(responseList);
    } catch (Exception e) {
      log.error("获取天气统计数据失败", e);
      return Result.error("获取天气统计数据失败：" + e.getMessage());
    }
  }
}